package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
)

func convertExcelToPDF(inputFilePath, outputDir string) error {
	// 获取输入文件的绝对路径
	absInputFilePath, err := filepath.Abs(inputFilePath)
	if err != nil {
		return fmt.Errorf("failed to get absolute path of input file: %v", err)
	}

	// 获取输出目录的绝对路径
	absOutputDir, err := filepath.Abs(outputDir)
	if err != nil {
		return fmt.Errorf("failed to get absolute path of output directory: %v", err)
	}

	// 构建 LibreOffice 命令行参数
	cmd := exec.Command("libreoffice", "--headless", "--convert-to", "pdf", absInputFilePath, "--outdir", absOutputDir)

	// 设置命令的标准输出和标准错误输出，以便捕获输出信息
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	// 运行命令
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error converting file: %v", err)
	}

	return nil
}

type Response struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		// r.ParseForm()
		file, _, err := r.FormFile("file")

		fileName := r.FormValue("file_name")
		if err != nil {
			http.Error(w, "Failed to read file", http.StatusBadRequest)
			return
		}
		if fileName == "" {
			fileName = "default"
		}
		defer file.Close()

		basePath, err := os.Getwd()
		if err != nil {
			http.Error(w, "Failed to get current path", http.StatusInternalServerError)
			return
		}

		filePath := fmt.Sprintf("%s/%s.xlsx", basePath, fileName)
		out, err := os.Create(filePath)
		if err != nil {
			http.Error(w, "Failed to create file", http.StatusInternalServerError)
			return
		}
		defer out.Close()

		_, err = io.Copy(out, file)
		if err != nil {
			http.Error(w, "Failed to save file", http.StatusInternalServerError)
			return
		}

		//转pdf
		// 调用转换函数
		outputDir := "./"
		var resp Response

		if err := convertExcelToPDF(filePath, outputDir); err != nil {
			fmt.Printf("Failed to convert file: %v\n", err)

			resp = Response{
				Code: -1,
				Msg:  fmt.Sprintf("Failed to convert file:%v", err),
				Data: nil,
			}

		} else {
			resp = Response{
				Code: 0,
				Msg:  "File converted successfully",
				Data: nil,
			}
		}

		jsonData, err := json.Marshal(resp)
		if err != nil {
			http.Error(w, "Error converting to json", http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")

		w.Write(jsonData)
	}
}

func downloadHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		http.Error(w, "Error parsing form", http.StatusBadRequest)
		return
	}
	fileName := r.FormValue("file_name")
	if fileName == "" {
		fileName = "default"
	}

	basePath, err := os.Getwd()
	if err != nil {
		http.Error(w, "Failed to get current path", http.StatusInternalServerError)
		return
	}
	file, err := os.Open(fmt.Sprintf("%s/%s.pdf", basePath, fileName))
	if err != nil {
		http.Error(w, "File not found", http.StatusNotFound)
		return
	}
	defer file.Close()

	io.Copy(w, file)
}

func main() {
	http.HandleFunc("/upload", uploadHandler)
	http.HandleFunc("/download", downloadHandler)
	fmt.Println("Server started at 8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Printf("server start failed,%s \n", err)
	}
}
